package com.yelobblog.yelobblog.Interceptor;

import com.yelobblog.yelobblog.common.untils.ThreadLocalUtil;
import com.yelobblog.yelobblog.common.untils.jwt;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        String requestMethod = request.getMethod();
        if ("OPTIONS".equals(requestMethod)) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        try {
            Map<String,Object> claims= jwt.parseToken(token);
            ThreadLocalUtil.set(claims);

            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ThreadLocalUtil.remove();
    }
}
